<?php
namespace app\admin\business;

use think\Exception;

class AdminUser {
    public static function login($data) {
        try {
            $adminUserObj = new \app\common\model\mysql\AdminUser();
            $adminUser = self::getAdminUserByUsername($data['username']);
            if (empty($adminUser)){
                throw new Exception('不存在该用户');
            }
            // 判断密码是否正确
            if ($adminUser['password'] != md5(md5($data['password']).$adminUser['salt'])){
                throw new Exception('密码错误');
            }
            // 需要记录信息到mysql表中
            $updateData = [
                'last_login_time'=>time(),
                'last_login_ip'=>request()->ip()
            ];
            $adminUserObj->updateById($adminUser['id'], $updateData);
        }catch (\Exception $e) {
            // todo 记录日志 $e->getMessage()
            throw new Exception('内部异常，登录失败');
        }
        // 记录session
        session(config('admin.session_admin'), $adminUser);
        return true;
    }

    public static function getAdminUserByUsername($username){
        $adminUserObj = new \app\common\model\mysql\AdminUser();
        $adminUser = $adminUserObj->getAdminUserByUsername($username);
        if (empty($adminUser) || $adminUser->status != config('status.mysql.table_normal')){
            return false;
        }
        $adminUser = $adminUser->toArray();
        return $adminUser;
    }
}